/* 
 * Copyright 2008 Lovely Systems GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lovely.gwt.jsonrpc.client;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Simple callback used for HTTP requests. Just repacks exceptions and calls
 * abstract deserialization method if HTTP result is OK.
 */
public abstract class JSONRequestCallback implements RequestCallback {
	private static final int HTTP_OK = 200;

	private AsyncCallback<Object> callback;

	public JSONRequestCallback(AsyncCallback<Object> callback) {
		this.callback = callback;
	}

	public void onError(Request request, Throwable exception) {
		callback.onFailure(exception);
	}

	public void onResponseReceived(Request request, Response response) {
		try {
			if (response.getStatusCode() == HTTP_OK) {
				JSONValue jsonValue = JSONParser.parse(response.getText());
				if (callback instanceof DebugAsyncCallback) {
					((DebugAsyncCallback<Object>) callback).afterReceive(jsonValue);
				}
				JSONObject jsonObj = jsonValue.isObject();
				if (jsonObj != null) {
					JSONValue result = jsonObj.get("result");
					if (result == null) {
						throw new JSONException("JsonRpc ERROR: no result");
					}
					JSONValue error = jsonObj.get("error");
					if (error != null) {
						throw new JSONException(error.toString());
					}

					callback.onSuccess(deserialize(result));
				} else {
					throw new JSONException("JsonRpc ERROR: invalid response");
				}
			} else {
				callback.onFailure(new JSONHttpException(response
						.getStatusCode(), response.getStatusText(), response
						.getText()));
			}
		} catch (JSONException e) {
			// could not parse JSON
			callback.onFailure(e);
		}
	}

	public abstract Object deserialize(JSONValue jsonValue);
}
